#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import os
import sys
import django
import requests
from io import BytesIO

# 添加项目路径到系统路径
backend_path = os.path.join(os.path.dirname(__file__), '..', 'backend')
sys.path.append(backend_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'massage_app.settings')

# 初始化Django
django.setup()

from backend.common.image_crawler import image_crawler
from services.models import Banner, Category, Technician, Service

def crawl_real_images():
    """爬取真实图片并保存到数据库"""
    # 清空现有数据
    Banner.objects.all().delete()
    Category.objects.all().delete()
    Technician.objects.all().delete()
    Service.objects.all().delete()
    
    # 定义要爬取的图片信息
    # 注意：以下URL仅为示例，在实际项目中应该使用真实的图片搜索API
    real_images = {
        "banners": [
            {
                "title": "秋季养生特惠",
                "description": "专业按摩服务，享受健康生活",
                "keyword": "massage",
                "sort_order": 1
            },
            {
                "title": "新用户专享",
                "description": "首次预约立减50元",
                "keyword": "spa",
                "sort_order": 2
            }
        ],
        "technicians": [
            {
                "name": "张技师",
                "keyword": "massage therapist",
                "rating": 4.8,
                "order_count": 128
            },
            {
                "name": "李技师",
                "keyword": "spa therapist",
                "rating": 4.9,
                "order_count": 96
            },
            {
                "name": "王技师",
                "keyword": "foot massage",
                "rating": 4.7,
                "order_count": 142
            }
        ],
        "services": [
            {
                "name": "全身放松按摩",
                "category": "massage",
                "description": "专业的全身放松按摩服务，缓解疲劳",
                "duration": 60,
                "price": 198.00,
                "keyword": "full body massage"
            },
            {
                "name": "足底按摩",
                "category": "footcare",
                "description": "专业的足底按摩服务，促进血液循环",
                "duration": 45,
                "price": 128.00,
                "keyword": "foot massage"
            }
        ]
    }
    
    # 爬取轮播图
    banner_urls = []
    for i, banner_info in enumerate(real_images["banners"]):
        print(f"爬取轮播图: {banner_info['title']}")
        # 尝试从网络爬取真实图片
        image_data = image_crawler.search_and_download_image(banner_info["keyword"])
        if image_data:
            # 调整图片大小
            image_data = image_crawler.resize_image(image_data, 600, 300)
            # 上传到MinIO
            url = image_crawler.upload_image(image_data, "banners", f"banner{i+1}.jpg")
            if url:
                banner_urls.append(url)
                print(f"轮播图上传成功: {banner_info['title']} -> {url}")
                
                # 保存到数据库
                Banner.objects.create(
                    title=banner_info["title"],
                    description=banner_info["description"],
                    image=url,
                    sort_order=banner_info["sort_order"]
                )
            else:
                print(f"轮播图上传失败: {banner_info['title']}")
        else:
            print(f"轮播图爬取失败: {banner_info['title']}")
    
    # 生成图标（使用SVG）
    icons = {
        "massage": ("按摩", "#888"),
        "spa": ("SPA", "#4a90e2"),
        "footcare": ("足疗", "#e24a6a"),
        "bodycare": ("身体护理", "#7ed321")
    }
    
    icon_urls = {}
    for name, (text, color) in icons.items():
        print(f"处理图标: {name}")
        url = image_crawler.process_icon(name, text, color)
        if url:
            icon_urls[name] = url
            print(f"图标上传成功: {name} -> {url}")
            
            # 保存到数据库
            Category.objects.create(
                name=name,
                icon=url,
                sort_order=list(icons.keys()).index(name) + 1
            )
        else:
            print(f"图标处理失败: {name}")
    
    # 爬取技师头像
    technician_urls = []
    for i, tech_info in enumerate(real_images["technicians"]):
        print(f"爬取技师头像: {tech_info['name']}")
        # 尝试从网络爬取真实图片
        image_data = image_crawler.search_and_download_image(tech_info["keyword"])
        if image_data:
            # 调整图片大小
            image_data = image_crawler.resize_image(image_data, 200, 200)
            # 上传到MinIO
            url = image_crawler.upload_image(image_data, "avatars", f"technician{i+1}.jpg")
            if url:
                technician_urls.append(url)
                print(f"技师头像上传成功: {tech_info['name']} -> {url}")
                
                # 保存到数据库
                Technician.objects.create(
                    name=tech_info["name"],
                    avatar=url,
                    rating=tech_info["rating"],
                    order_count=tech_info["order_count"]
                )
            else:
                print(f"技师头像上传失败: {tech_info['name']}")
        else:
            print(f"技师头像爬取失败: {tech_info['name']}")
    
    # 爬取服务图片
    service_urls = []
    for i, service_info in enumerate(real_images["services"]):
        print(f"爬取服务图片: {service_info['name']}")
        # 尝试从网络爬取真实图片
        image_data = image_crawler.search_and_download_image(service_info["keyword"])
        if image_data:
            # 调整图片大小
            image_data = image_crawler.resize_image(image_data, 200, 200)
            # 上传到MinIO
            url = image_crawler.upload_image(image_data, "services", f"service{i+1}.jpg")
            if url:
                service_urls.append(url)
                print(f"服务图片上传成功: {service_info['name']} -> {url}")
                
                # 保存到数据库
                Service.objects.create(
                    name=service_info["name"],
                    category=service_info["category"],
                    description=service_info["description"],
                    duration=service_info["duration"],
                    price=service_info["price"],
                    image=url
                )
            else:
                print(f"服务图片上传失败: {service_info['name']}")
        else:
            print(f"服务图片爬取失败: {service_info['name']}")
    
    print("所有真实图片已爬取、上传并保存到数据库")
    
    return {
        "banners": banner_urls,
        "icons": icon_urls,
        "technicians": technician_urls,
        "services": service_urls
    }

if __name__ == "__main__":
    urls = crawl_real_images()
    print("\n爬取的图片URL:")
    for category, url_list in urls.items():
        print(f"\n{category}:")
        if isinstance(url_list, dict):
            for name, url in url_list.items():
                print(f"  {name}: {url}")
        else:
            for i, url in enumerate(url_list):
                print(f"  {i+1}: {url}")